from datetime import datetime, timedelta, timezone
from typing import Any, Union

import jwt
from passlib.context import CryptContext

from fastapi.security import OAuth2PasswordBearer
from app.core.config import settings

# 密码加密算法
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


ALGORITHM = "HS256"


def create_access_token(subject: dict, expires_delta: Union[timedelta, None] = None) -> str:
    """
    生成token
    :param subject:
        user_id: 用户id
        username: 用户名
        is_super: 是否超级管理员
    :param expires_delta:
    :return:
    """
    to_encode = subject.copy()
    # 过期时间
    if expires_delta:
        expire = datetime.now(timezone.utc) + expires_delta
    else:
        expire = datetime.now(timezone.utc) + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt



def get_password_hash(password: str) -> str:
    """
    密码加密
    :param password:
    :return: 加密后的密码
    """
    return pwd_context.hash(password)


def verify_password(plain_password: str, hashed_password: str) -> bool:
    """
    密码校验
    :param plain_password: 用户输入的密码
    :param hashed_password: 数据库密码
    :return: Boolean
    """
    return pwd_context.verify(plain_password, hashed_password)



